unit Main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, RzTabs, AdvNavBar, RzPanel, ImgList, RzStatus, RzDBStat,
  ExtCtrls, RzButton, DB, ADODB, StdCtrls, RzCmboBx, RzDBCmbo, DBCtrls,
  RzDBSpin, RzDBEdit, Mask, RzEdit, RzCommon, RzLstBox, ComCtrls, RzDTP,
  RzDBDTP, RzLabel, Grids, BaseGrid, AdvGrid, DBAdvGrid, DBAdvGrd, RzRadChk,strutils,
  QuickRpt, QRCtrls,QRPDFFilt,ComObj,ShellAPI, jpeg, RzTreeVw, RzChkLst,
  kbmMemTable, gtPDFCrypt, gtClasses, gtCstPDFDoc, gtExPDFDoc,
  gtExProPDFDoc, gtPDFDoc, RzDBChk,DateUtils, Series, TeEngine, TeeProcs,
  Chart, RzSpnEdt;

type

  TInstObj = class(TObject)
    InstKey: Integer;
    Name: string;
    Branch: string;
  end;
  
  TfrmMainWindow = class(TForm)
    PageMainMenu: TRzPageControl;
    TSTaskMan: TRzTabSheet;
    TSRegistration: TRzTabSheet;
    RzStatusBar1: TRzStatusBar;
    RzStatusPane1: TRzStatusPane;
    RzClockStatus1: TRzClockStatus;
    RzProgressStatus1: TRzProgressStatus;
    RzVersionInfoStatus1: TRzVersionInfoStatus;
    RzFieldStatus1: TRzFieldStatus;
    RzResourceStatus1: TRzResourceStatus;
    RzDBStateStatus1: TRzDBStateStatus;
    RzDBStateStatus2: TRzDBStateStatus;
    TSPayroll: TRzTabSheet;
    CGISImageList: TImageList;
    RzPanel1: TRzPanel;
    RzPanel2: TRzPanel;
    btnHighPriority: TRzBitBtn;
    btnCompleted: TRzBitBtn;
    NavBarTaskMan: TAdvNavBar;
    NavBarPanelTask: TAdvNavBarPanel;
    NavBarPanelReports: TAdvNavBarPanel;
    NavBarPanelSettings: TAdvNavBarPanel;
    btnSaveNew: TRzBitBtn;
    btnNew: TRzBitBtn;
    RzListBox1: TRzListBox;
    rzFrameFormatCGIS: TRzFrameController;
    RzListBox2: TRzListBox;
    TaskManTaskList: TRzListBox;
    TaskManMainPanel: TRzPanel;
    TaskManEntryListPage: TRzPageControl;
    TabSheet1: TRzTabSheet;
    TabSheet2: TRzTabSheet;
    fldSubject: TRzDBEdit;
    fldDateEnd: TRzDBDateTimeEdit;
    fldPercentage: TRzDBSpinEdit;
    fldAssigned: TRzDBLookupComboBox;
    fldStatus: TRzDBComboBox;
    fldPriority: TRzDBComboBox;
    dsTask: TDataSource;
    QryTask: TADODataSet;
    ADOConnection1: TADOConnection;
    RzLabel1: TRzLabel;
    RzLabel2: TRzLabel;
    RzLabel3: TRzLabel;
    RzLabel4: TRzLabel;
    RzLabel5: TRzLabel;
    RzLabel6: TRzLabel;
    RzLabel7: TRzLabel;
    fldDateStart: TRzDBDateTimeEdit;
    QryAssignee: TADODataSet;
    dsAssignee: TDataSource;
    btnCancel: TRzBitBtn;
    btnSaveExit: TRzBitBtn;
    RzLabel8: TRzLabel;
    fldRemarks: TRzDBMemo;
    QryTaskList: TADODataSet;
    dsTaskList: TDataSource;
    dbgridTask: TDBAdvStringGrid;
    RzPanel3: TRzPanel;
    btnMarkPassed: TRzBitBtn;
    btnPrintRebates: TRzBitBtn;
    btnSaveBilling: TRzBitBtn;
    btnRebates: TRzBitBtn;
    btnBilling: TRzBitBtn;
    btnSaveRebates: TRzBitBtn;
    RzPanel4: TRzPanel;
    RzPanel5: TRzPanel;
    RegEntryPage: TRzPageControl;
    RzTabSheet2: TRzTabSheet;
    RzTabSheet3: TRzTabSheet;
    dbGridReviewee: TDBAdvStringGrid;
    QryReviewee: TADODataSet;
    dsReviewee: TDataSource;
    NavBarPanelPassers: TAdvNavBar;
    RegPanelListRebates: TAdvNavBarPanel;
    RzGroupBox1: TRzGroupBox;
    chkFilterByDateRange: TRzCheckBox;
    RzLabel17: TRzLabel;
    RzLabel18: TRzLabel;
    RegPanelListSchools: TAdvNavBarPanel;
    RegPanelListCompany: TAdvNavBarPanel;
    RegPanelListEndorser: TAdvNavBarPanel;
    RegPanelListRank: TAdvNavBarPanel;
    RegPanelListPassers: TAdvNavBarPanel;
    RegPanelListBranch: TAdvNavBarPanel;
    dsBranch: TDataSource;
    QryBranch: TADODataSet;
    QryRank: TADODataSet;
    dsRank: TDataSource;
    QrySchool: TADODataSet;
    dsSchool: TDataSource;
    QryCompany: TADODataSet;
    dsCompany: TDataSource;
    QryEndorser: TADODataSet;
    dsEndorser: TDataSource;
    ListBranches: TRzListBox;
    btnFilterReg: TRzBitBtn;
    filterDateStart: TRzDateTimePicker;
    filterDateEnd: TRzDateTimePicker;
    chkFilterWithEndorser: TRzCheckBox;
    QryRebates: TADODataSet;
    dsRebates: TDataSource;
    QryEmployee: TADODataSet;
    dsEmployee: TDataSource;
    QryEditReviewee: TADODataSet;
    dsEditReviewee: TDataSource;
    QryRevieweeRebates: TADODataSet;
    dsRevieweeRebates: TDataSource;
    filterName: TRzEdit;
    RzLabel16: TRzLabel;
    chkSetAsDatePassed: TRzCheckBox;
    filterDatePassed: TRzDateTimePicker;
    ListMonthYear: TRzListBox;
    chkFilterOnlyPassers: TRzCheckBox;
    AdvNavBarPanel1: TAdvNavBarPanel;
    ListRebates: TRzListBox;
    btnTaskRefresh: TRzBitBtn;
    QryBranchLookup: TADODataSet;
    dsBranchLookup: TDataSource;
    RzPanel6: TRzPanel;
    RzLabel9: TRzLabel;
    RzLabel10: TRzLabel;
    RzLabel11: TRzLabel;
    RzLabel14: TRzLabel;
    RzLabel21: TRzLabel;
    RzLabel20: TRzLabel;
    fldRebatesKey: TRzDBEdit;
    fldRebatesCode: TRzDBEdit;
    fldRebStartDate: TRzDBDateTimeEdit;
    fldRebEndDate: TRzDBDateTimeEdit;
    fldRebPreparedby: TRzDBLookupComboBox;
    RzLabel19: TRzLabel;
    RzLabel22: TRzLabel;
    RzLabel12: TRzLabel;
    RzLabel13: TRzLabel;
    RzLabel15: TRzLabel;
    fldRebNotedby: TRzDBLookupComboBox;
    fldRebCheckedby: TRzDBLookupComboBox;
    fldRebApprovedby: TRzDBLookupComboBox;
    fldRebBranch: TRzDBLookupComboBox;
    RzPanel7: TRzPanel;
    dbgridRevieweeRebates: TDBAdvStringGrid;
    TabSheet3: TRzTabSheet;
    RzPanel9: TRzPanel;
    QryRebatesView: TADODataSet;
    dsRebatesView: TDataSource;
    TabSheet4: TRzTabSheet;
    QryRebatesList: TADODataSet;
    dsRebatesList: TDataSource;
    dbgridBilling: TDBAdvStringGrid;
    RzPanel8: TRzPanel;
    RzLabel23: TRzLabel;
    RzLabel24: TRzLabel;
    RzLabel25: TRzLabel;
    RzLabel26: TRzLabel;
    RzLabel27: TRzLabel;
    RzLabel28: TRzLabel;
    RzLabel29: TRzLabel;
    RzLabel30: TRzLabel;
    RzLabel31: TRzLabel;
    RzLabel33: TRzLabel;
    fldBillKey: TRzDBEdit;
    fldBillCode: TRzDBEdit;
    fldBillDate: TRzDBDateTimeEdit;
    fldBillTo: TRzDBLookupComboBox;
    fldBillPreparedBy: TRzDBLookupComboBox;
    fldBillApprovedBy: TRzDBLookupComboBox;
    fldBillBranch: TRzDBLookupComboBox;
    QryBilling: TADODataSet;
    dsBilling: TDataSource;
    fldBillType: TRzDBComboBox;
    RzLabel32: TRzLabel;
    QryRevieweeBilling: TADODataSet;
    dsRevieweeBilling: TDataSource;
    AdvNavBarPanel2: TAdvNavBarPanel;
    listBilling: TRzListBox;
    QryBillingList: TADODataSet;
    dsBillingList: TDataSource;
    RzPanel10: TRzPanel;
    RzBitBtn1: TRzBitBtn;
    RzBitBtn2: TRzBitBtn;
    RzBitBtn3: TRzBitBtn;
    RzBitBtn4: TRzBitBtn;
    RzBitBtn5: TRzBitBtn;
    RzBitBtn6: TRzBitBtn;
    QuickRep1: TQuickRep;
    QRBand1: TQRBand;
    QRBand2: TQRBand;
    QRDBText1: TQRDBText;
    QRDBText2: TQRDBText;
    QRDBText3: TQRDBText;
    QRDBText4: TQRDBText;
    QRDBText5: TQRDBText;
    QRDBText6: TQRDBText;
    QRShape1: TQRShape;
    QRLabel1: TQRLabel;
    QRLabel2: TQRLabel;
    QRLabel3: TQRLabel;
    QRLabel4: TQRLabel;
    QRLabel5: TQRLabel;
    QRLabel6: TQRLabel;
    QRBand3: TQRBand;
    QRLabel7: TQRLabel;
    lblRBTCode: TQRLabel;
    QRBand4: TQRBand;
    QRLabel8: TQRLabel;
    QRLabel9: TQRLabel;
    QRLabel10: TQRLabel;
    QRLabel11: TQRLabel;
    lblPreparedby: TQRLabel;
    lblCheckedby: TQRLabel;
    lblNotedby: TQRLabel;
    lblApprovedby: TQRLabel;
    QRSysData1: TQRSysData;
    QRLabel12: TQRLabel;
    QRExpr1: TQRExpr;
    QRShape2: TQRShape;
    QRShape3: TQRShape;
    QRShape4: TQRShape;
    QRShape5: TQRShape;
    QRShape6: TQRShape;
    QRSysData2: TQRSysData;
    QRSysData3: TQRSysData;
    QRLabel13: TQRLabel;
    QuickRep4: TQuickRep;
    QRBand10: TQRBand;
    QRLabel42: TQRLabel;
    QRLBBillTo: TQRLabel;
    QRImage3: TQRImage;
    QRLabel47: TQRLabel;
    QRLabel43: TQRLabel;
    QRLBStatementNo: TQRLabel;
    QRShape18: TQRShape;
    QRLabel44: TQRLabel;
    QRLabel46: TQRLabel;
    QRLabel48: TQRLabel;
    QRLabel52: TQRLabel;
    QRBand11: TQRBand;
    QRDBText24: TQRDBText;
    QRDBText25: TQRDBText;
    QRDBText26: TQRDBText;
    QRDBText27: TQRDBText;
    QRBand12: TQRBand;
    QRShape21: TQRShape;
    QRLabel78: TQRLabel;
    QRLabel79: TQRLabel;
    QRShape23: TQRShape;
    QRLabel83: TQRLabel;
    QRLabel84: TQRLabel;
    QRBand13: TQRBand;
    QRShape24: TQRShape;
    QRShape14: TQRShape;
    QRLabel53: TQRLabel;
    QRLabel14: TQRLabel;
    QRSysData4: TQRSysData;
    QRExpr2: TQRExpr;
    QRLabel15: TQRLabel;
    QRShape7: TQRShape;
    QRExpr3: TQRExpr;
    QRExpr4: TQRExpr;
    QRLabel16: TQRLabel;
    lblBillingPreparedBy: TQRLabel;
    lblBillingApprovedBy: TQRLabel;
    btnPrintBilling: TRzBitBtn;
    QRLabel17: TQRLabel;
    QRLabel18: TQRLabel;
    AdvNavBar1: TAdvNavBar;
    AdvNavBarPanel9: TAdvNavBarPanel;
    RzListBox4: TRzListBox;
    AdvNavBarPanel3: TAdvNavBarPanel;
    RzListBox3: TRzListBox;
    AdvNavBarPanel4: TAdvNavBarPanel;
    RzListBox5: TRzListBox;
    RzPanel11: TRzPanel;
    RzPanel12: TRzPanel;
    HRPageControl: TRzPageControl;
    TabSheet5: TRzTabSheet;
    RzPanel13: TRzPanel;
    RzPanel14: TRzPanel;
    RzPanel15: TRzPanel;
    RzCheckTree_EmpList: TRzCheckTree;
    RzPanel16: TRzPanel;
    RzPanel17: TRzPanel;
    RzCheckList_names: TRzCheckList;
    RzBitBtn7: TRzBitBtn;
    RzBitBtn8: TRzBitBtn;
    RzDBLookupComboBox1: TRzDBLookupComboBox;
    RzDBLookupComboBox2: TRzDBLookupComboBox;
    RzBitBtn9: TRzBitBtn;
    TabSheet6: TRzTabSheet;
    RzPanel18: TRzPanel;
    RzPanel19: TRzPanel;
    adqTemp: TADOQuery;
    ADOConnection2: TADOConnection;
    cboInstructor: TRzComboBox;
    RzLabel34: TRzLabel;
    Qry2EvalResult: TADODataSet;
    ds2EvalResult: TDataSource;
    dbgridInsEvalResult: TDBAdvStringGrid;
    RzBitBtn10: TRzBitBtn;
    Mem2EvalResultSorted: TkbmMemTable;
    ds2EvalResultSorted: TDataSource;
    Mem2EvalResultSortedIEEVALQTEXT: TStringField;
    Mem2EvalResultSortedTTLX: TIntegerField;
    Mem2EvalResultSortedTTLY: TIntegerField;
    Mem2EvalResultSortedTTLZ: TFloatField;
    Mem2EvalResultSortedSORTKEY: TIntegerField;
    Qry2EvalSortKey: TADODataSet;
    ds2EvalSortKey: TDataSource;
    cbEvalResultDR: TRzCheckBox;
    dtEvalResultFrom: TRzDateTimePicker;
    RzLabel35: TRzLabel;
    dtEvalResultTo: TRzDateTimePicker;
    RzLabel36: TRzLabel;
    btnIERPrint: TRzBitBtn;
    gtPDFDocument1: TgtPDFDocument;
    listCompany: TRzListBox;
    TabSheet7: TRzTabSheet;
    RzPanel21: TRzPanel;
    RzLabel48: TRzLabel;
    RzLabel49: TRzLabel;
    RzLabel54: TRzLabel;
    RzLabel56: TRzLabel;
    RzLabel57: TRzLabel;
    fldSHIPPINGNAME: TRzDBEdit;
    RzPanel20: TRzPanel;
    fldADDRESS: TRzDBEdit;
    fldDefContactPerson: TRzDBEdit;
    fldDefCPPosition: TRzDBEdit;
    fldDefCPPhone: TRzDBEdit;
    fldDefCPMobile: TRzDBEdit;
    RzLabel37: TRzLabel;
    fldShipREMARKS: TRzDBEdit;
    RzLabel38: TRzLabel;
    dbgridCompany: TDBAdvStringGrid;
    TabSheet8: TRzTabSheet;
    RzPanel22: TRzPanel;
    RzLabel39: TRzLabel;
    RzLabel40: TRzLabel;
    RzLabel45: TRzLabel;
    fldEENDORSERFULL: TRzDBEdit;
    fldEENDORSERFIRST: TRzDBEdit;
    fldEREMARKS: TRzDBEdit;
    fldEENDORSERLAST: TRzDBEdit;
    RzLabel46: TRzLabel;
    fldEENDORSERMIDDLE: TRzDBEdit;
    RzLabel50: TRzLabel;
    fldEOLDFLAG: TRzDBCheckBox;
    RzPanel23: TRzPanel;
    dbgridEndorser: TDBAdvStringGrid;
    listEndorser: TRzListBox;
    QRMemoBContact: TQRMemo;
    RzLabel41: TRzLabel;
    fldBillBILLINGCODEEDITED: TRzDBEdit;
    TabSheet9: TRzTabSheet;
    RzBitBtn11: TRzBitBtn;
    Chart1: TChart;
    Series1: TBarSeries;
    Chart2: TChart;
    BarSeries1: TPieSeries;
    RzGroupBox2: TRzGroupBox;
    AdvStringGrid1: TAdvStringGrid;
    gridEmpEvaluation: TAdvStringGrid;
    QryEvalQuestioner: TADODataSet;
    dsEvalQuestioner: TDataSource;
    TabSheet10: TRzTabSheet;
    RzPanel24: TRzPanel;
    RzBitBtn18: TRzBitBtn;
    RzBitBtn12: TRzBitBtn;
    RzBitBtn13: TRzBitBtn;
    MainPageEmpEval: TRzPageControl;
    RzTabSheet1: TRzTabSheet;
    RzPanel25: TRzPanel;
    RzPanel26: TRzPanel;
    spinEmpSubject: TRzSpinButtons;
    edtActiveForEvaluation: TRzEdit;
    RzEdit1: TRzEdit;
    RzBitBtn14: TRzBitBtn;
    RzBitBtn15: TRzBitBtn;
    RzBitBtn16: TRzBitBtn;
    DBAdvStringGrid1: TDBAdvStringGrid;
    RzTabSheet4: TRzTabSheet;
    RzPanel35: TRzPanel;
    RzPanel36: TRzPanel;
    btnSubjectRemove: TRzBitBtn;
    btnSubjectAdd: TRzBitBtn;
    btnSubjectSearch: TRzBitBtn;
    edtSearchSubject: TRzEdit;
    spineditSubject: TRzSpinButtons;
    edtCurrentNameEmp: TRzEdit;
    cbMainFilterNavbar: TRzCheckBox;
    dbgridEvaluationSummary: TDBAdvStringGrid;
    procedure btnNewClick(Sender: TObject);
    procedure btnSaveNewClick(Sender: TObject);
    procedure btnSaveExitClick(Sender: TObject);
    procedure btnCancelClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure TaskManTaskListClick(Sender: TObject);
    procedure btnCompletedClick(Sender: TObject);
    procedure btnHighPriorityClick(Sender: TObject);
    procedure dbgridTaskDblClick(Sender: TObject);
    procedure dbgridTaskClick(Sender: TObject);
    procedure ListBranchesClick(Sender: TObject);
    procedure btnFilterRegClick(Sender: TObject);
    procedure btnRebatesClick(Sender: TObject);
    procedure btnSaveRebatesClick(Sender: TObject);
    procedure dbGridRevieweeClick(Sender: TObject);
    procedure btnMarkPassedClick(Sender: TObject);
    procedure chkSetAsDatePassedClick(Sender: TObject);
    procedure ListMonthYearClick(Sender: TObject);
    procedure btnTaskRefreshClick(Sender: TObject);
    procedure ListRebatesClick(Sender: TObject);
    procedure FilterQryRebatesReviewee;
    procedure FilterQryBillingReviewee;
    procedure fldRebStartDateChange(Sender: TObject);
    procedure fldRebEndDateChange(Sender: TObject);
    procedure fldRebBranchClick(Sender: TObject);
    procedure btnBillingClick(Sender: TObject);
    procedure fldBillToClick(Sender: TObject);
    procedure fldBillBranchClick(Sender: TObject);
    procedure btnSaveBillingClick(Sender: TObject);
    procedure listBillingClick(Sender: TObject);
    procedure btnPrintRebatesClick(Sender: TObject);
    procedure FileFind(Path, FileName, Ext: string);
    procedure btnPrintBillingClick(Sender: TObject);
    procedure RzBitBtn1Click(Sender: TObject);
    procedure RzCheckTree_EmpListDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure RzCheckList_namesClick(Sender: TObject);
    procedure RzBitBtn7Click(Sender: TObject);
    procedure RzBitBtn8Click(Sender: TObject);
    procedure RzBitBtn9Click(Sender: TObject);
    procedure RzBitBtn10Click(Sender: TObject);
    procedure btnIERPrintClick(Sender: TObject);
    procedure listCompanyClick(Sender: TObject);
    procedure listEndorserClick(Sender: TObject);
    procedure RzBitBtn11Click(Sender: TObject);
    procedure RzBitBtn12Click(Sender: TObject);
    procedure RzBitBtn15Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    iDefUser:integer;
    iDefUserFName:string;
    iSubDirectory,NewFilename,sCGConnOL,sLocalCEBUGEMSHRIS :String;
    procedure AssignedToGrid(iNoCols:integer;iNoRows:integer;iDesignedID:integer;sGridTitle:string);

  end;

var
  frmMainWindow: TfrmMainWindow;

implementation

uses Reports, POManagement, MainEvaluation, RequestItems, RequestEntry;

{$R *.dfm}

procedure TfrmMainWindow.btnNewClick(Sender: TObject);
begin
     TaskManEntryListPage.ActivePageIndex:=0;
     QryTask.Append;
     fldSubject.SetFocus;

     //Set Defaults
     QryTask.FieldByName('STARTDATE').AsDateTime:=Now();
     QryTask.FieldByName('CREATEDDATE').AsDateTime:=Now();
     QryTask.FieldByName('MODIFIEDDATE').AsDateTime:=Now();
     QryTask.FieldByName('COMPLETEPER').AsInteger:=0;
     QryTask.FieldByName('ACTUALWORK').AsInteger:=0;
     QryTask.FieldByName('TOTALWORK').AsInteger:=0;
     QryTask.FieldByName('STATUS').AsString:='Not Started';
     QryTask.FieldByName('PRIORITY').AsString:='Normal';
     QryTask.FieldByName('ASSGNEDBYKEY').AsInteger:=iDefUser;
     QryTask.FieldByName('CREATEDBYKEY').AsInteger:=iDefUser;
     QryTask.FieldByName('MODIFIEDBYKEY').AsInteger:=iDefUser;

     btnNew.Enabled:=False;
     btnSaveNew.Enabled:=True;
     btnSaveExit.Enabled:=True;
     btnCancel.Enabled:=True;
     btnHighPriority.Enabled:=False;
     btnCompleted.Enabled:=False;

end;

procedure TfrmMainWindow.btnSaveNewClick(Sender: TObject);
begin
     TaskManEntryListPage.ActivePageIndex:=0;
     QryTask.Post;
     btnTaskRefreshClick(Sender);
     QryTask.Append;
     //Set Defaults
     QryTask.FieldByName('STARTDATE').AsDateTime:=Now();
     QryTask.FieldByName('CREATEDDATE').AsDateTime:=Now();
     QryTask.FieldByName('MODIFIEDDATE').AsDateTime:=Now();
     QryTask.FieldByName('COMPLETEPER').AsInteger:=0;
     QryTask.FieldByName('ACTUALWORK').AsInteger:=0;
     QryTask.FieldByName('TOTALWORK').AsInteger:=0;
     QryTask.FieldByName('STATUS').AsString:='Not Started';
     QryTask.FieldByName('PRIORITY').AsString:='Normal';
     QryTask.FieldByName('ASSGNEDBYKEY').AsInteger:=iDefUser;
     QryTask.FieldByName('CREATEDBYKEY').AsInteger:=iDefUser;
     QryTask.FieldByName('MODIFIEDBYKEY').AsInteger:=iDefUser;

     btnNew.Enabled:=False;
     btnSaveNew.Enabled:=True;
     btnSaveExit.Enabled:=True;
     btnCancel.Enabled:=True;
     btnHighPriority.Enabled:=False;
     btnCompleted.Enabled:=False;


end;

procedure TfrmMainWindow.btnSaveExitClick(Sender: TObject);
begin
     TaskManEntryListPage.ActivePageIndex:=0;
     QryTask.Post;
     Self.Close;
end;

procedure TfrmMainWindow.btnCancelClick(Sender: TObject);
begin
     TaskManEntryListPage.ActivePageIndex:=0;
     QryTask.Cancel;
     btnNew.Enabled:=True;
     btnSaveNew.Enabled:=False;
     btnSaveExit.Enabled:=False;
     btnCancel.Enabled:=False;
     btnHighPriority.Enabled:=True;
     btnCompleted.Enabled:=True;

end;

procedure TfrmMainWindow.FormShow(Sender: TObject);
VAR
   i:integer;
begin

     filterDateStart.DateTime := IncDay(Now(),-30);
     filterDateEnd.DateTime :=IncDay(Now(),1);


  sCGConnOL := 'Provider=SQLOLEDB.1'
          + ';Password=Gems@2014'
          + ';Persist Security Info=True'
          + ';User ID=CEBUGEMSHRIS'
          + ';Initial Catalog=CEBUGEMSHRIS'
//          + ';Data Source=CEBUGEMSHRIS.db.6779690.hostedresource.com';
          + ';Data Source=tcp:192.168.0.111\SQLEXPRESS,1433';

  sLocalCEBUGEMSHRIS := 'Provider=SQLOLEDB.1'
           + ';Password=mdoffice'
           + ';Persist Security Info=True'
           + ';User ID=sa'
           + ';Initial Catalog=CEBUGEMSHRIS'
           + ';Data Source=TOSHIBA\SQLEXPRESS';


     ADOConnection2.ConnectionString:=sCGConnOL;
     ADOConnection2.Connected;

     QryEmployee.Open;
     QryBranch.Open;
     QryRank.Open;
     QrySchool.Open;
     QryCompany.Open;

     QryEndorser.Open;
     QryBranchLookup.Open;
     QryAssignee.Open;
     QryReviewee.Open;
     QryEditReviewee.Open;

     QryRebatesView.Open;
     QryTaskList.Open;
     QryTask.Open;
     //QryRevieweeRebates.Open;

     QryRebates.Open;
     QryRebatesList.Open;

     QryBilling.Open;
     QryBillingList.Open;

     


     QryBranch.First;
     ListBranches.Items.Add('All');
     for i:=0 to QryBranch.RecordCount-1 do
     begin
          ListBranches.Items.Add(trim(QryBranch.fieldbyname('branchname').AsString));
          QryBranch.Next;
     end;

     QryCompany.First;
     for i:=0 to QryCompany.RecordCount-1 do
     begin
          listCompany.Items.Add(trim(QryCompany.fieldbyname('SHIPPINGNAME').AsString));
          QryCompany.Next;
     end;

     QryEndorser.First;
     for i:=0 to QryEndorser.RecordCount-1 do
     begin
          listEndorser.Items.Add(trim(QryEndorser.fieldbyname('ENDORSERFULL').AsString));
          QryEndorser.Next;
     end;


     QryRebatesList.First;
     for i:=0 to QryRebatesList.RecordCount-1 do
     begin
          ListRebates.Items.Add(trim(QryRebatesList.fieldbyname('RBTCODE').AsString));
          QryRebatesList.Next;
     end;

     QryBillingList.First;
     for i:=0 to QryBillingList.RecordCount-1 do
     begin
          listBilling.Items.Add(trim(QryBillingList.fieldbyname('BILLINGCODE').AsString));
          QryBillingList.Next;
     end;

     filterDateStart.DateTime:=Now();
     filterDateEnd.DateTime:=Now();     
     TaskManEntryListPage.ActivePageIndex:=1;
     HRPageControl.ActivePageIndex:=0;     
end;

procedure TfrmMainWindow.TaskManTaskListClick(Sender: TObject);
begin
     TaskManEntryListPage.ActivePageIndex:=1;
     QryTaskList.Filtered:=False;
     case TaskManTaskList.ItemIndex of
          0:
            begin
                 QryTaskList.Filter:='ASSIGNEDTOKEY=' + IntToStr(iDefUser) + ' and Status<>''Completed''';
                 QryTaskList.Filtered:=True;
            end;
          1:
            begin
                 QryTaskList.Filter:='Status=''Completed''';
                 QryTaskList.Filtered:=True;
            end;
          2:
            begin
                 QryTaskList.Filter:='ASSGNEDBYKEY=' + IntToStr(iDefUser);
                 QryTaskList.Filtered:=True;
            end;
          3:
            begin
                 QryTaskList.Filter:='Priority=''High'' and ASSIGNEDTOKEY=' + IntToStr(iDefUser);
                 QryTaskList.Filtered:=True;
            end;
          4:
            begin
                 QryTaskList.Filter:='ENDDATE>''' + formatdatetime('mm-dd-yyyy',now()) + ''' and ASSGNEDBYKEY=' + IntToStr(iDefUser);
                 QryTaskList.Filtered:=True;
            end;

     end;
end;

procedure TfrmMainWindow.btnCompletedClick(Sender: TObject);
begin
     QryTask.Locate('TASKKEY',dbgridTask.Cells[9,dbgridTask.Row],[]);
     QryTask.Edit;
     QryTask.FieldByName('Status').AsString:='Completed';
     QryTask.FieldByName('DATECOMPLETED').AsDateTime:=Now();
     QryTask.FieldByName('COMPLETEPER').AsInteger:=100;
     QryTask.Post;

     if trim(QryTask.FieldByName('TASKTYPE').AsString)='REBATES' then
     begin
           QryRebatesList.Locate('REBATESKEY',QryTask.FieldByName('LINKKEY').AsString,[]);
           QryRebatesList.Edit;
           QryRebatesList.FieldByName(QryTask.FieldByName('UPDATEFIELD').AsString).AsString:='Y';
           QryRebatesList.Post;
     end;

     ShowMessage('Task has been mark Completed.');
     QryTaskList.Requery;
     dbgridTask.Refresh;
end;

procedure TfrmMainWindow.btnHighPriorityClick(Sender: TObject);
begin
     QryTask.Locate('TASKKEY',dbgridTask.Cells[8,dbgridTask.Row],[]);
     QryTask.Edit;
     QryTask.FieldByName('Priority').AsString:='High';
//     QryTask.FieldByName('DATECOMPLETED').AsDateTime:=Now();
     QryTask.Post;
     ShowMessage('Task has been mark as High Priority.');
     QryTaskList.Requery;
     dbgridTask.Refresh;
end;

procedure TfrmMainWindow.dbgridTaskDblClick(Sender: TObject);
begin

     QryTask.Locate('TASKKEY',dbgridTask.Cells[8,dbgridTask.Row],[]);
     QryTask.Edit;
     TaskManEntryListPage.ActivePageIndex:=0;
     fldSubject.SetFocus;
     btnNew.Enabled:=False;

end;

procedure TfrmMainWindow.dbgridTaskClick(Sender: TObject);
begin
     if QryTaskList.FieldByName('ASSGNEDBYKEY').AsInteger=iDefUser then
     begin
        if QryTaskList.FieldByName('ASSIGNEDTOKEY').AsInteger= iDefUser then
           btnCompleted.Enabled:=true
        else
           btnCompleted.Enabled:=False;
     end else
         btnCompleted.Enabled:=True;
end;

procedure TfrmMainWindow.ListBranchesClick(Sender: TObject);
begin

     RegEntryPage.ActivePageIndex:=1;
     //showmessage('BRANCHNAME=''' + trim(ListBranches.SelectedItem) +'''');
     if trim(ListBranches.SelectedItem)<>'All' then
     begin
      QryReviewee.Filter:='BRANCHNAME=''' + trim(ListBranches.SelectedItem) +'''';
      QryReviewee.Filtered:=True;
     end else
           QryReviewee.Filtered:=False;
end;

procedure TfrmMainWindow.btnFilterRegClick(Sender: TObject);
var
 i:integer;
 strSQL:string;
begin
     if chkFilterByDateRange.Checked then
     begin
          strSQL:='select A.*, B.RANKNAME,C.SHIPPINGNAME,D.SCHOOLNAME,E.ENDORSERFULL,'+
                     ' upper(CONCAT(A.LASTNAME, '', '',A.FIRSTNAME)) as RevieweeFull,convert(varchar,A.DATEENROLL,110) as fDATEENROLL' +
                     ' from REVIEWER A' +
                     ' left join RANK B on B.RANKKEY=A.RANKKEY' +
                     ' left join SHIPPING C on C.SHIPPINGKEY=A.SHIPPINGKEY' +
                     ' left join SCHOOL D on D.SCHOOLKEY=A.SCHOOLKEY' +
                     ' left join ENDORSER E on E.ENDORSERKEY=A.ENDORSERKEY';

          if chkFilterOnlyPassers.Checked then
             strSQL:=strSQL + ' where a.REVSTATUS=''Passed'' and a.DATEENROLL between ''' + formatdatetime('yyyy-mm-dd',FilterDateStart.datetime) + ' 00:00'' and ''' + formatdatetime('yyyy-mm-dd',FilterDateEnd.datetime) + ' 23:59'''
          else
              strSQL:=strSQL + ' where a.REBATESKEY is null and a.LASTNAME is not null and a.DATEENROLL between ''' + formatdatetime('yyyy-mm-dd',FilterDateStart.datetime) + ' 00:00'' and ''' + formatdatetime('yyyy-mm-dd',FilterDateEnd.datetime) + ' 23:59''';

          if chkFilterWithEndorser.Checked then
             strSQL:=strSQL + ' and a.endorserkey is not null';

          QryReviewee.Close;
          QryReviewee.CommandText:=strSQL + ' order by a.DATEENROLL desc';
          QryReviewee.Open;

          strSQL:='Select distinct upper(BRANCHNAME) as BRANCHNAME from REVIEWER where LASTNAME is not null and BRANCHNAME is not null';
          if chkFilterOnlyPassers.Checked then
             strSQL:=strSQL + ' and DATEPASSED between ''' + formatdatetime('yyyy-mm-dd',FilterDateStart.datetime) + ' 00:00'' and ''' + formatdatetime('yyyy-mm-dd',FilterDateEnd.datetime) + ' 23:59'''
          else
              strSQL:=strSQL + ' and DATEENROLL between ''' + formatdatetime('yyyy-mm-dd',FilterDateStart.datetime) + ' 00:00'' and ''' + formatdatetime('yyyy-mm-dd',FilterDateEnd.datetime) + ' 23:59''';

          if chkFilterWithEndorser.Checked then
             strSQL:=strSQL + ' and endorserkey is not null';

          QryBranch.Close;
          QryBranch.CommandText:=strSQL + ' order by BRANCHNAME';

          QryBranch.Open;

          ListBranches.Clear;
         QryBranch.First;
         ListBranches.Items.Add('All');
         for i:=0 to QryBranch.RecordCount-1 do
         begin
              ListBranches.Items.Add(trim(QryBranch.fieldbyname('branchname').AsString));
              QryBranch.Next;
         end;
     end else
     begin
          strSQL:='select A.*, B.RANKNAME,C.SHIPPINGNAME,D.SCHOOLNAME,E.ENDORSERFULL,'+
                     ' upper(CONCAT(A.LASTNAME, '', '',A.FIRSTNAME)) as RevieweeFull,convert(varchar,A.DATEENROLL,110) as fDATEENROLL' +
                     ' from REVIEWER A' +
                     ' left join RANK B on B.RANKKEY=A.RANKKEY' +
                     ' left join SHIPPING C on C.SHIPPINGKEY=A.SHIPPINGKEY' +
                     ' left join SCHOOL D on D.SCHOOLKEY=A.SCHOOLKEY' +
                     ' left join ENDORSER E on E.ENDORSERKEY=A.ENDORSERKEY' +
                     ' where a.LASTNAME is not null';
          if chkFilterWithEndorser.Checked then
             strSQL:=strSQL + ' and a.endorserkey is not null';
          if trim(filterName.Text)<>'' then
             strSQL:=strSQL + ' and CONCAT(A.LASTNAME, '', '',A.FIRSTNAME) like ''%' + trim(filterName.Text) + '%''';


          QryReviewee.Close;
          QryReviewee.CommandText:=strSQL + ' order by a.DATEENROLL desc';
          QryReviewee.Open;

          strSQL:='Select distinct upper(BRANCHNAME) as BRANCHNAME from REVIEWER where LASTNAME is not null and BRANCHNAME is not null';

          if chkFilterWithEndorser.Checked then
             strSQL:=strSQL + ' and endorserkey is not null';
          if trim(filterName.Text)<>'' then
             strSQL:=strSQL + ' and CONCAT(LASTNAME, '', '',FIRSTNAME) like ''%' + trim(filterName.Text) + '%''';

          QryBranch.Close;
          QryBranch.CommandText:=strSQL + ' order by BRANCHNAME';

          QryBranch.Open;

          ListBranches.Clear;
         QryBranch.First;
         ListBranches.Items.Add('All');         
         for i:=0 to QryBranch.RecordCount-1 do
         begin
              ListBranches.Items.Add(trim(QryBranch.fieldbyname('branchname').AsString));
              QryBranch.Next;
         end;

     end;
end;

procedure TfrmMainWindow.btnRebatesClick(Sender: TObject);

begin
     RegEntryPage.ActivePageIndex:=0;
     QryRebates.Append;
     QryRebates.FieldByName('DATESTART').AsDateTime :=filterDateStart.DateTime;
     QryRebates.FieldByName('DATEEND').AsDateTime :=filterDateEnd.DateTime;
     QryRebates.FieldByName('PREPAREDBY').AsString :='118';
     QryRebates.FieldByName('CHECKEDBY').AsString :='2';
     QryRebates.FieldByName('NOTEDBY').AsString :='69';
     QryRebates.FieldByName('APPROVEDBY').AsString :='68';
     fldRebStartDate.SetFocus;
     btnRebates.Enabled:=False;
     btnSaveRebates.Enabled:=True;
     //btnAddRebates.Enabled:=False;
end;

procedure TfrmMainWindow.btnSaveRebatesClick(Sender: TObject);
function GetRBTCode(strBranch:string):integer;
begin
   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConnection1;
     SQL.Text := 'SELECT * FROM rebates ' +
            ' WHERE BRANCH = ''' + strBranch + ''' order by 1 desc';
     try
       Open;
     except
       Exit;
     end;

     //showmessage(RightStr(trim(FieldByName('RBTCODE').AsString),4));
     if not IsEmpty then
        result:=strtoint(trim(StringReplace(RightStr(trim(FieldByName('RBTCODE').AsString),4), '0', '',[rfReplaceAll, rfIgnoreCase])))
     else
        result:=0;

   finally
     Free;
   end;
end;
var
i:integer;
begin

     if trim(fldRebBranch.Text)='' then
     begin
       Application.MessageBox('Field Branch is required.', 'Field required', MB_ICONEXCLAMATION);
       fldRebBranch.SetFocus;
       Exit;
     end;

     if trim(fldRebStartDate.Text)='' then
     begin
       Application.MessageBox('Field Start date is required.', 'Field required', MB_ICONEXCLAMATION);
       fldRebStartDate.SetFocus;
       Exit;
     end;

     if trim(fldRebEndDate.Text)='' then
     begin
       Application.MessageBox('Field End date is required.', 'Field required', MB_ICONEXCLAMATION);
       fldRebEndDate.SetFocus;
       Exit;
     end;
     QryRebates.FieldByName('RBTCODE').AsString:= 'RBT - ' + fldRebBranch.ListSource.DataSet.fieldbyname('ABBR').AsString  + ' - ' + RightStr('0000' + inttostr(GetRBTCode(trim(fldRebBranch.Text)) +1),4);     
     QryRebates.Post;
     QryRevieweeRebates.First;
     for i:=1 to QryRevieweeRebates.RecordCount do
     begin
         QryEditReviewee.Locate('REVIEWERKEY',dbgridRevieweeRebates.Cells[8,i],[]);
         QryEndorser.Locate('ENDORSERKEY',QryEditReviewee.FieldByName('ENDORSERKEY').AsInteger,[]);
         QryEditReviewee.Edit;
         QryEditReviewee.FieldByName('REBATESKEY').AsString:=QryRebates.FieldByName('REBATESKEY').AsString;

         IF TRIM(QryEndorser.FieldByName('OLDFLAG').AsString)='Y' then
         begin
              if QryEditReviewee.FieldByName('REVIEWERFEE').AsFloat>29500 then
                 QryEditReviewee.FieldByName('REBATESAMT').AsFloat:=2000
              else
                 QryEditReviewee.FieldByName('REBATESAMT').AsFloat:=1000
         end else
             QryEditReviewee.FieldByName('REBATESAMT').AsFloat:=500;

         QryEditReviewee.FieldByName('REBATESFLAG').AsString:='N';
         QryEditReviewee.Post;
         //ShowMessage('Reviewee ' + QryEditReviewee.FieldByName('LASTNAME').AsString + ' has been added for rebates.');
         QryRevieweeRebates.Next;
     end;

     QryRebates.Requery;
     QryRebates.First;
     ListRebates.Clear;
     for i:=0 to QryRebates.RecordCount-1 do
     begin
          ListRebates.Items.Add(trim(QryRebates.fieldbyname('RBTCODE').AsString));
          QryRebates.Next;
     end;
     

     //ADD TO TASK
     IF TRIM(QryRebates.FieldByName('CHECKEDBY').AsString)<>'' THEN
     BEGIN
       QryTask.Append;
       QryTask.FieldByName('STARTDATE').AsDateTime:=Now();
       QryTask.FieldByName('CREATEDDATE').AsDateTime:=Now();
       QryTask.FieldByName('MODIFIEDDATE').AsDateTime:=Now();
       QryTask.FieldByName('COMPLETEPER').AsInteger:=0;
       QryTask.FieldByName('ACTUALWORK').AsInteger:=0;
       QryTask.FieldByName('TOTALWORK').AsInteger:=0;
       QryTask.FieldByName('STATUS').AsString:='Not Started';
       QryTask.FieldByName('PRIORITY').AsString:='High';
       QryTask.FieldByName('TASKTYPE').AsString:='REBATES';
       QryTask.FieldByName('UPDATEFIELD').AsString:='CHECKED';
       QryTask.FieldByName('SUBJECT').AsString:='PLESE CHECKED REBATES ' + QryRebates.FieldByName('RBTCODE').AsString;
       QryTask.FieldByName('LINKKEY').AsString:=QryRebates.FieldByName('REBATESKEY').AsString;
       QryTask.FieldByName('ASSGNEDBYKEY').AsInteger:=iDefUser;
       QryTask.FieldByName('ASSIGNEDTOKEY').AsString:=TRIM(QryRebates.FieldByName('CHECKEDBY').AsString);
       QryTask.FieldByName('CREATEDBYKEY').AsInteger:=iDefUser;
       QryTask.FieldByName('MODIFIEDBYKEY').AsInteger:=iDefUser;
       QryTask.Post;
     END;
     //ADD TO TASK
     IF TRIM(QryRebates.FieldByName('NOTEDBY').AsString)<>'' THEN
     BEGIN
       QryTask.Append;
       QryTask.FieldByName('STARTDATE').AsDateTime:=Now();
       QryTask.FieldByName('CREATEDDATE').AsDateTime:=Now();
       QryTask.FieldByName('MODIFIEDDATE').AsDateTime:=Now();
       QryTask.FieldByName('COMPLETEPER').AsInteger:=0;
       QryTask.FieldByName('ACTUALWORK').AsInteger:=0;
       QryTask.FieldByName('TOTALWORK').AsInteger:=0;
       QryTask.FieldByName('STATUS').AsString:='Not Started';
       QryTask.FieldByName('PRIORITY').AsString:='High';
       QryTask.FieldByName('TASKTYPE').AsString:='REBATES';
       QryTask.FieldByName('UPDATEFIELD').AsString:='NOTED';
       QryTask.FieldByName('SUBJECT').AsString:='PLESE NOTE REBATES ' + QryRebates.FieldByName('RBTCODE').AsString;
       QryTask.FieldByName('LINKKEY').AsString:=QryRebates.FieldByName('REBATESKEY').AsString;
       QryTask.FieldByName('ASSGNEDBYKEY').AsInteger:=iDefUser;
       QryTask.FieldByName('ASSIGNEDTOKEY').AsString:=TRIM(QryRebates.FieldByName('NOTEDBY').AsString);
       QryTask.FieldByName('CREATEDBYKEY').AsInteger:=iDefUser;
       QryTask.FieldByName('MODIFIEDBYKEY').AsInteger:=iDefUser;
       QryTask.Post;
     END;
     //ADD TO TASK
     IF TRIM(QryRebates.FieldByName('APPROVEDBY').AsString)<>'' THEN
     BEGIN
       QryTask.Append;
       QryTask.FieldByName('STARTDATE').AsDateTime:=Now();
       QryTask.FieldByName('CREATEDDATE').AsDateTime:=Now();
       QryTask.FieldByName('MODIFIEDDATE').AsDateTime:=Now();
       QryTask.FieldByName('COMPLETEPER').AsInteger:=0;
       QryTask.FieldByName('ACTUALWORK').AsInteger:=0;
       QryTask.FieldByName('TOTALWORK').AsInteger:=0;
       QryTask.FieldByName('STATUS').AsString:='Not Started';
       QryTask.FieldByName('PRIORITY').AsString:='High';
       QryTask.FieldByName('TASKTYPE').AsString:='REBATES';
       QryTask.FieldByName('UPDATEFIELD').AsString:='APPROVED';
       QryTask.FieldByName('SUBJECT').AsString:='PLESE APPROVED REBATES ' + QryRebates.FieldByName('RBTCODE').AsString;
       QryTask.FieldByName('LINKKEY').AsString:=QryRebates.FieldByName('REBATESKEY').AsString;
       QryTask.FieldByName('ASSGNEDBYKEY').AsInteger:=iDefUser;
       QryTask.FieldByName('ASSIGNEDTOKEY').AsString:=TRIM(QryRebates.FieldByName('APPROVEDBY').AsString);
       QryTask.FieldByName('CREATEDBYKEY').AsInteger:=iDefUser;
       QryTask.FieldByName('MODIFIEDBYKEY').AsInteger:=iDefUser;
       QryTask.Post;
     END;


     btnRebates.Enabled:=True;
     btnSaveRebates.Enabled:=False;
     //btnAddRebates.Enabled:=True;
     QryTaskList.Requery;
     dbgridTask.Refresh;

end;

procedure TfrmMainWindow.dbGridRevieweeClick(Sender: TObject);
begin
     if TRIM(QryReviewee.FieldByName('REBATESKEY').AsString)<>'' THEN
        //btnAddRebates.Enabled:=fALSE
     ELSE
          //btnAddRebates.Enabled:=TRUE;
end;

procedure TfrmMainWindow.btnMarkPassedClick(Sender: TObject);
begin

     QryEditReviewee.Locate('REVIEWERKEY',dbGridReviewee.Cells[8,dbGridReviewee.Row],[]);
     QryEditReviewee.Edit;
     QryEditReviewee.FieldByName('REVSTATUS').AsString:='PASSED';
     if chkSetAsDatePassed.Checked then
          QryEditReviewee.FieldByName('DATEPASSED').AsDateTime:=filterDatePassed.DateTime;
     QryEditReviewee.Post;
     ShowMessage('Reviewee has been mark as passed.' + formatdatetime('mm-dd-yy',filterDatePassed.DateTime));
     QryReviewee.Requery;
     dbGridReviewee.Refresh;
     QryRevieweeRebates.Requery;
     dbgridRevieweeRebates.Refresh;

end;

procedure TfrmMainWindow.chkSetAsDatePassedClick(Sender: TObject);
begin
     if chkSetAsDatePassed.Checked then
     begin
        filterDatePassed.Enabled:=true;
        filterDatePassed.DateTime:=Now();
     end else
        filterDatePassed.Enabled:=False;

end;

procedure TfrmMainWindow.ListMonthYearClick(Sender: TObject);
begin
     RegEntryPage.ActivePageIndex:=1;
     chkFilterOnlyPassers.Checked:=True;     
     QryReviewee.Filtered:=fALSE;
     case ListMonthYear.ItemIndex of
          0:
            begin
             //showmessage('BRANCHNAME=''' + trim(ListBranches.SelectedItem) +'''');
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date :=StrToDate('01/01/2015');
             filterDateEnd.Date:=StrToDate('01/31/2015');
            end;
          1:
            begin
             //showmessage('BRANCHNAME=''' + trim(ListBranches.SelectedItem) +'''');
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('02/01/2015');
             filterDateEnd.Date:=StrToDate('02/20/2015');
            end;
          2:
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('03/01/2015');
             filterDateEnd.Date:=StrToDate('03/20/2015');
            end;
          3:
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('04/01/2015');
             filterDateEnd.Date:=StrToDate('04/20/2015');
            end;
          4:
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('05/01/2015');
             filterDateEnd.Date:=StrToDate('05/20/2015');
            end;
          5:
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('06/01/2015');
             filterDateEnd.Date:=StrToDate('06/20/2015');
            end;
          6:
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('07/01/2015');
             filterDateEnd.Date:=StrToDate('07/30/2015');
            end;
          7:
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('08/01/2015');
             filterDateEnd.Date:=StrToDate('08/31/2015');
            end;
          8:
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('09/01/2015');
             filterDateEnd.Date:=StrToDate('09/30/2015');
            end;
          9:
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('10/01/2015');
             filterDateEnd.Date:=StrToDate('10/31/2015');
            end;
          10:
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('11/01/2015');
             filterDateEnd.Date:=StrToDate('11/30/2015');
            end;
          11:
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('12/01/2015');
             filterDateEnd.Date:=StrToDate('12/31/2015');
            end;
     else
            begin
             chkFilterByDateRange.Checked:=True;
             filterDateStart.Date:=StrToDate('06/01/2015');
             filterDateEnd.Date:=StrToDate('06/20/2015');
            end;

     end;

     btnFilterRegClick(Sender);
end;

procedure TfrmMainWindow.btnTaskRefreshClick(Sender: TObject);
begin
     QryTaskList.Requery;
     dbgridTask.Refresh;
end;

procedure TfrmMainWindow.ListRebatesClick(Sender: TObject);
begin
     RegEntryPage.ActivePageIndex:=0;
     QryRebates.Locate('RBTCODE',trim(ListRebates.SelectedItem),[]);
     FilterQryRebatesReviewee;
end;

procedure TfrmMainWindow.FilterQryRebatesReviewee;
var
strSQL:string;
begin
     strSQL:= 'select A.*, B.RANKNAME,C.SHIPPINGNAME,D.SCHOOLNAME,E.ENDORSERFULL, upper(CONCAT(A.LASTNAME, '', '',A.FIRSTNAME)) as RevieweeFull,convert(varchar,A.DATEENROLL,110) as fDATEENROLL' +
              ' from REVIEWER A' +
              ' left join RANK B on B.RANKKEY=A.RANKKEY' +
              ' left join SHIPPING C on C.SHIPPINGKEY=A.SHIPPINGKEY' +
              ' left join SCHOOL D on D.SCHOOLKEY=A.SCHOOLKEY' +
              ' left join ENDORSER E on E.ENDORSERKEY=A.ENDORSERKEY' +
              ' where a.LASTNAME is not null and A.ENDORSERKEY is not null and E.ENDORSERFULL not like ''%WALK%''';


     if (trim(fldRebStartDate.Text)<>'') and (trim(fldRebEndDate.Text)<>'') then
        strSQL:=strSQL + ' and a.DATEENROLL between ''' + formatdatetime('yyyy-mm-dd',fldRebStartDate.DataSource.DataSet.FieldByName('DATESTART').AsDateTime) + ' 00:00'' and ''' + formatdatetime('yyyy-mm-dd',fldRebEndDate.DataSource.Dataset.FieldByName('DATEEND').AsDateTime) + ' 23:59''';
     if Trim(fldRebBranch.Text)<>'' then
        strSQL:=strSQL + ' and a.BRANCHNAME=''' + Trim(fldRebBranch.Text) + '''';
     if trim(fldRebatesKey.Text)<>'' then
        strSQL:=strSQL + ' and a.REBATESKEY=' + trim(fldRebatesKey.Text);

     with QryRevieweeRebates do
     begin
          Close;
          CommandText:= strSQL + ' order by a.DATEENROLL desc';
          Open;
          Requery;
     end;

     dbgridRevieweeRebates.Refresh;
end;

procedure TfrmMainWindow.FilterQryBillingReviewee;
var
strSQL:string;
begin
     strSQL:= 'select A.*, B.RANKNAME,C.SHIPPINGNAME,D.SCHOOLNAME,E.ENDORSERFULL, upper(CONCAT(A.LASTNAME, '', '',A.FIRSTNAME)) as RevieweeFull,convert(varchar,A.DATEENROLL,110) as fDATEENROLL' +
              ' from REVIEWER A' +
              ' left join RANK B on B.RANKKEY=A.RANKKEY' +
              ' left join SHIPPING C on C.SHIPPINGKEY=A.SHIPPINGKEY' +
              ' left join SCHOOL D on D.SCHOOLKEY=A.SCHOOLKEY' +
              ' left join ENDORSER E on E.ENDORSERKEY=A.ENDORSERKEY' +
              ' where a.LASTNAME is not null';


     if trim(fldBillTo.Text)<>'' then
        strSQL:=strSQL + ' and A.SHIPPINGKEY =' + Trim(fldBillTo.ListSource.DataSet.fieldbyname('SHIPPINGKEY').AsString);
     if Trim(fldBillBranch.Text)<>'' then
        strSQL:=strSQL + ' and a.BRANCHNAME=''' + Trim(fldBillBranch.Text) + '''';
     if trim(fldBillKey.Text)<>'' then
        strSQL:=strSQL + ' and a.BILLINGKEY=' + trim(fldBillKey.Text);

     with QryRevieweeBilling do
     begin
          Close;
          CommandText:= strSQL + ' order by a.DATEENROLL desc';
          Open;
          Requery;
     end;

     dbgridBilling.Refresh;
end;


procedure TfrmMainWindow.fldRebStartDateChange(Sender: TObject);
begin
     FilterQryRebatesReviewee;
end;

procedure TfrmMainWindow.fldRebEndDateChange(Sender: TObject);
begin
     FilterQryRebatesReviewee;
end;

procedure TfrmMainWindow.fldRebBranchClick(Sender: TObject);
begin
     FilterQryRebatesReviewee;
end;

procedure TfrmMainWindow.btnBillingClick(Sender: TObject);
begin
     RegEntryPage.ActivePageIndex:=2;
     QryBilling.Append;
     QryBilling.FieldByName('BILLINGDATE').AsDateTime :=Now();
     QryBilling.FieldByName('TRANSACTIONDATE').AsDateTime :=Now();
     QryBilling.FieldByName('BILLINGTYPE').AsString :='Company';
     QryBilling.FieldByName('PREPAREDBY').AsString :='2';
     QryBilling.FieldByName('APPROVEDBY').AsString :='68';
     QryBilling.FieldByName('STATUS').AsString :='A';     
     fldBillDate.SetFocus;
     btnBilling.Enabled:=False;
     btnSaveBilling.Enabled:=True;
     btnRebates.Enabled:=False;
     btnSaveRebates.Enabled:=False;
     btnPrintRebates.Enabled:=False;
     btnMarkPassed.Enabled:=False;

end;

procedure TfrmMainWindow.fldBillToClick(Sender: TObject);
begin
     FilterQryBillingReviewee;
end;

procedure TfrmMainWindow.fldBillBranchClick(Sender: TObject);
begin
     FilterQryBillingReviewee;
end;

procedure TfrmMainWindow.btnSaveBillingClick(Sender: TObject);
function GetRBTCode(strBranch:string):integer;
begin
   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConnection1;
     SQL.Text := 'SELECT * FROM billing ' +
            ' WHERE BRANCH = ''' + strBranch + ''' order by 1 desc';
     try
       Open;
     except
       Exit;
     end;

     showmessage(RightStr(trim(FieldByName('BILLINGCODE').AsString),4));
     if not IsEmpty then
        result:=strtoint(trim(StringReplace(RightStr(trim(FieldByName('BILLINGCODE').AsString),4), '0', '',[rfReplaceAll, rfIgnoreCase])))
     else
        result:=0;

   finally
     Free;
   end;
end;
var
i:integer;
begin

     if trim(fldBillBranch.Text)='' then
     begin
       Application.MessageBox('Field Branch is required.', 'Field required', MB_ICONEXCLAMATION);
       fldBillBranch.SetFocus;
       Exit;
     end;

     if trim(fldBillDate.Text)='' then
     begin
       Application.MessageBox('Field Bill date is required.', 'Field required', MB_ICONEXCLAMATION);
       fldBillDate.SetFocus;
       Exit;
     end;

     if trim(fldBillTo.Text)='' then
     begin
       Application.MessageBox('Field Bill to is required.', 'Field required', MB_ICONEXCLAMATION);
       fldBillDate.SetFocus;
       Exit;
     end;
     QryBilling.FieldByName('BILLINGCODE').AsString:= 'BILL - ' + fldBillBranch.ListSource.DataSet.fieldbyname('ABBR').AsString  + ' - ' + RightStr('0000' + inttostr(GetRBTCode(trim(fldBillBranch.Text)) +1),4);     
     QryBilling.Post;
     QryRevieweeBilling.First;
//     dbgridBilling.is1
     showmessage(inttostr(dbgridBilling.SelectedRowCount));
    // dbgridBilling.DataSource.DataSet.First;
     for i:=1 to dbgridBilling.DataSource.DataSet.RecordCount do
     begin
         IF dbgridBilling.SelectedRow[i]=i THEN
         BEGIN
         QryEditReviewee.Locate('REVIEWERKEY',dbgridBilling.Cells[8,i],[]);
         QryEditReviewee.Edit;
         QryEditReviewee.FieldByName('BILLINGKEY').AsString:=QryBilling.FieldByName('BILLINGKEY').AsString;
         QryEditReviewee.FieldByName('BILLINGAMT').AsFloat:=QryEditReviewee.FieldByName('REVIEWERFEE').AsFloat;
         QryEditReviewee.FieldByName('BILLINGVAT').AsFloat:=((QryEditReviewee.FieldByName('REVIEWERFEE').AsFloat*12)/100);
         QryEditReviewee.Post;
         ShowMessage('Reviewee ' + QryEditReviewee.FieldByName('LASTNAME').AsString + ' has been added for billing.');
         END;
         dbgridBilling.DataSource.DataSet.Next;
     end;

     QryBilling.Requery;
     QryBilling.First;
     listBilling.Clear;
     for i:=0 to QryBilling.RecordCount-1 do
     begin
          listBilling.Items.Add(trim(QryBilling.fieldbyname('BILLINGCODE').AsString));
          QryBilling.Next;
     end;
     

        //ADD TO TASK
     IF TRIM(QryBilling.FieldByName('APPROVEDBY').AsString)<>'' THEN
     BEGIN
       QryTask.Append;
       QryTask.FieldByName('STARTDATE').AsDateTime:=Now();
       QryTask.FieldByName('CREATEDDATE').AsDateTime:=Now();
       QryTask.FieldByName('MODIFIEDDATE').AsDateTime:=Now();
       QryTask.FieldByName('COMPLETEPER').AsInteger:=0;
       QryTask.FieldByName('ACTUALWORK').AsInteger:=0;
       QryTask.FieldByName('TOTALWORK').AsInteger:=0;
       QryTask.FieldByName('STATUS').AsString:='Not Started';
       QryTask.FieldByName('PRIORITY').AsString:='High';
       QryTask.FieldByName('TASKTYPE').AsString:='BILLING';
       QryTask.FieldByName('UPDATEFIELD').AsString:='APPROVED';
       QryTask.FieldByName('SUBJECT').AsString:='PLESE APPROVED BILLING ' + QryBilling.FieldByName('BILLINGCODE').AsString;
       QryTask.FieldByName('LINKKEY').AsString:=QryBilling.FieldByName('BILLINGKEY').AsString;
       QryTask.FieldByName('ASSGNEDBYKEY').AsInteger:=iDefUser;
       QryTask.FieldByName('ASSIGNEDTOKEY').AsString:=TRIM(QryBilling.FieldByName('APPROVEDBY').AsString);
       QryTask.FieldByName('CREATEDBYKEY').AsInteger:=iDefUser;
       QryTask.FieldByName('MODIFIEDBYKEY').AsInteger:=iDefUser;
       QryTask.Post;
     END;


     btnBilling.Enabled:=True;
     btnSaveBilling.Enabled:=False;
     btnRebates.Enabled:=True;
     btnSaveRebates.Enabled:=False;
     btnPrintRebates.Enabled:=False;
     btnMarkPassed.Enabled:=False;
     //btnAddRebates.Enabled:=True;
     QryTaskList.Requery;
     dbgridTask.Refresh;
end;

procedure TfrmMainWindow.listBillingClick(Sender: TObject);
begin
     RegEntryPage.ActivePageIndex:=2;
     QryBilling.Locate('BILLINGCODE',trim(listBilling.SelectedItem),[]);
     FilterQryBillingReviewee;
end;

procedure TfrmMainWindow.btnPrintRebatesClick(Sender: TObject);
var
  repPDF:TQRPDFDocumentFilter;
begin
     lblRBTCode.Caption:=trim(fldRebatesCode.text);
     lblPreparedby.Caption:=trim(fldRebPreparedby.text);
     lblCheckedby.Caption:=trim(fldRebCheckedby.text);
     lblNotedby.Caption:=trim(fldRebNotedby.text);
     lblApprovedby.Caption:=trim(fldRebApprovedby.text);

    iSubDirectory:=ExtractFilePath(Application.ExeName) + 'Reports';
    FileFind(iSubDirectory,'*','pdf'); // delete existing pdf in the folder.
    NewFilename := '';
    if not DirectoryExists(iSubDirectory) then MkDir(iSubDirectory);
    NewFilename:=iSubDirectory+'\'+CreateClassID+'.pdf';
    repPDF := TQRPDFDocumentFilter.Create(NewFilename);
    QuickRep1.ExportToFilter(repPDF);

    ShellExecute(Handle, 'OPEN', PChar(NewFilename), nil, nil, SW_SHOW);

end;

procedure TfrmMainWindow.FileFind(Path, FileName, Ext: string);
var
  SearchRec: TSearchRec;
  FindResult: Integer;
  S: string;
begin
  S := Path + '\' + FileName + '.' + Ext;
  FindResult := FindFirst(S, faAnyFile, SearchRec);
  while FindResult = 0 do
  begin
    if ((SearchRec.Name <> '.') and (SearchRec.Name <> '..')) then
      if not ((SearchRec.Attr and faDirectory) > 0) then
      begin
        if not DeleteFile(iSubDirectory + '\' + SearchRec.Name) then
        begin
        end;
      end;
    FindResult := FindNext(SearchRec);
  end;
  SysUtils.FindClose(SearchRec);
end;


procedure TfrmMainWindow.btnPrintBillingClick(Sender: TObject);
var
  repPDF:TQRPDFDocumentFilter;
begin

     QRMemoBContact.Lines.Clear;
     lblBillingPreparedBy.Caption:=trim(fldBillPreparedBy.text);
     lblBillingApprovedBy.Caption:=trim(fldBillApprovedBy.text);
     QRLBStatementNo.Caption:='STATEMENT NO.:' + UpperCase(trim(fldBillBILLINGCODEEDITED.Text)); ;
     QRLBBillTo.Caption:= 'BILL TO:' + UpperCase(trim(fldBillTo.Text));

     QRMemoBContact.Lines.Add(UpperCase(trim(fldBillTo.ListSource.DataSet.fieldbyname('DefContactPerson').AsString)));
     QRMemoBContact.Lines.Add(UpperCase(trim(fldBillTo.ListSource.DataSet.fieldbyname('DefCPPosition').AsString)));
     QRMemoBContact.Lines.Add(trim(fldBillTo.ListSource.DataSet.fieldbyname('ADDRESS').AsString));
     QRMemoBContact.Lines.Add('Mobile:' + trim(fldBillTo.ListSource.DataSet.fieldbyname('DefCPMobile').AsString) + '  Phone:' + trim(fldBillTo.ListSource.DataSet.fieldbyname('DefCPPhone').AsString));
     QRMemoBContact.Lines.Add('Email:' + trim(fldBillTo.ListSource.DataSet.fieldbyname('DefCPEmail').AsString));

    iSubDirectory:=ExtractFilePath(Application.ExeName) + 'Reports';
    FileFind(iSubDirectory,'*','pdf'); // delete existing pdf in the folder.
    NewFilename := '';
    if not DirectoryExists(iSubDirectory) then MkDir(iSubDirectory);
    NewFilename:=iSubDirectory+'\'+CreateClassID+'.pdf';
    repPDF := TQRPDFDocumentFilter.Create(NewFilename);
    QuickRep4.ExportToFilter(repPDF);

    ShellExecute(Handle, 'OPEN', PChar(NewFilename), nil, nil, SW_SHOW);

end;

procedure TfrmMainWindow.RzBitBtn1Click(Sender: TObject);
var
   AFrmTemp : TfrmEvaluatonModule;
begin
  AFrmTemp:= TfrmEvaluatonModule.Create(nil);
  AFrmTemp.ADOConnection1:=ADOConnection1;
  AFrmTemp.Caption := 'Employee Evaluation Module';
  AFrmTemp.MainPageEmpEval.HideAllTabs;
  AFrmTemp.iDefUser:=iDefUser;
  AFrmTemp.ShowModal;
  FreeAndNil(AFrmTemp);;

     {
     QryEvalQuestioner.Connection:= ADOConnection1;
     QryEvalQuestioner.Open;

     iCount:=QryEvalQuestioner.RecordCount;

     AssignedToGrid(8,iCount*4,0,'EvaluationGrid');

     QryEmployee.Open;
     QryEmployee.First;
     while not QryEmployee.Eof do
     begin
          RzCheckTree_EmpList.Items.Add(RzCheckTree_EmpList.Items.GetFirstNode,QryEmployee.fieldbyname('DTRLINKNAME').AsString);
          RzCheckList_names.Add(QryEmployee.fieldbyname('DTRLINKNAME').AsString);
          QryEmployee.Next;
     end;
      }

end;
procedure TfrmMainWindow.AssignedToGrid(iNoCols:integer;iNoRows:integer;iDesignedID:integer;sGridTitle:string);
begin
//
end;

procedure TfrmMainWindow.RzCheckTree_EmpListDragDrop(Sender,
  Source: TObject; X, Y: Integer);
begin

     showmessage(RzCheckTree_EmpList.PathFromNode(RzCheckTree_EmpList.Selected));
end;

procedure TfrmMainWindow.RzCheckList_namesClick(Sender: TObject);
var
i:integer;
begin
     for i:=0 to RzCheckList_names.Count-1 do
     begin
          if RzCheckList_names.ItemChecked[i]=true then
             showmessage(RzCheckList_names.Items.Strings[i]);
     end;

end;

procedure TfrmMainWindow.RzBitBtn7Click(Sender: TObject);
var
i:integer;
begin
     for i:=0 to RzCheckList_names.Count-1 do
     begin
          if RzCheckList_names.ItemChecked[i]=true then
             RzCheckTree_EmpList.Items.AddChild(RzCheckTree_EmpList.Selected,RzCheckList_names.Items.Strings[i])
     end;

end;


procedure TfrmMainWindow.RzBitBtn8Click(Sender: TObject);
var
i:integer;
begin

     for i:=0 to RzCheckTree_EmpList.Items.Count-1 do
     begin
          //showmessage(RzCheckTree_EmpList.PathFromNode(RzCheckTree_EmpList.Items.Item[i]));
     end;

     showmessage('Saving Items Success...');
end;

procedure TfrmMainWindow.RzBitBtn9Click(Sender: TObject);
procedure generateCBIns;
var
AInstObj:TInstObj;
begin
  with adqTemp do begin
    Close;
    Connection:=ADOConnection2;
    CommandTimeout := 6000; //sarma on jan.23.2013
    SQL.Text := 'select EMPLOYEECODE,DTRLINKNAME,BRANCHNAME from employee where DEPARTMENT like ''%REVIEW INSTRUCTOR%'' order by DTRLINKNAME';
    Open;
    if not IsEmpty then
    begin
      cboInstructor.ClearItems;

      AInstObj := TInstObj.Create;
      AInstObj.InstKey := 0;
      AInstObj.Name := '';
      AInstObj.Branch := '';
      cboInstructor.Items.AddObject('', AInstObj);

      First;
      while not Eof do begin
        AInstObj := TInstObj.Create;
        AInstObj.InstKey := FieldByName('EMPLOYEECODE').AsInteger;
        AInstObj.Name := UpperCase(FieldByName('DTRLINKNAME').AsString);
        AInstObj.Branch := UpperCase(FieldByName('BRANCHNAME').AsString);
        cboInstructor.Items.AddObject(AInstObj.Name, AInstObj);
        Next;
      end;
    end;
  end;
end;
begin
HRPageControl.ActivePageIndex:=1;
generateCBIns;
cboInstructor.DroppedDown;
cboInstructor.SetFocus;

end;

procedure TfrmMainWindow.RzBitBtn10Click(Sender: TObject);
var
strSQLER:string;
begin
    if trim(cboInstructor.Text)='' then
     begin
       Application.MessageBox('Instructor is required.', 'Field required', MB_ICONEXCLAMATION);
       cboInstructor.SetFocus;
       cboInstructor.DroppedDown;
       Exit;
     end;

     if Trim(cboInstructor.Text)<>'' then
     begin
       strSQLER:= 'SELECT B.IEEVALQTEXT, SUM(B.IEEVALRATE) AS TTLX,COUNT(IEEVALRATE) AS TTLY, CAST(SUM(B.IEEVALRATE)/CAST(COUNT(IEEVALRATE) AS MONEY) AS DECIMAL(18,2)) AS TTLZ' +
                   ' FROM IE A' +
                   ' LEFT JOIN IERESULTS B ON B.IEKEY=A.IEKEY' +
                   ' WHERE A.IEINAME=''' + Trim(cboInstructor.Text) + '''';
       if cbEvalResultDR.Checked then
          strSQLER:= strSQLER +' AND A.IEDOE between ''' + formatdatetime('yyyy-mm-dd',dtEvalResultFrom.datetime) + ' 00:00'' and ''' + formatdatetime('yyyy-mm-dd',dtEvalResultto.datetime) + ' 23:59''';

       with Qry2EvalResult do
       begin
          Close;
          Connection:=ADOConnection2;
          CommandTimeout := 6000; //sarma on jan.23.2013
          CommandText := strSQLER  +
                   ' GROUP BY B.IEEVALQTEXT';
          Open;

          Mem2EvalResultSorted.EmptyTable;
          if not IsEmpty then
          begin
            First;
            Qry2EvalSortKey.Open;
            while not Eof do begin
              with Mem2EvalResultSorted do
              begin
                   Open;
                   Append;
                   Qry2EvalSortKey.Locate('EVALDESC',trim(Qry2EvalResult.FieldByName('IEEVALQTEXT').AsString),[]);
                   FieldByName('SORTKEY').AsInteger:=Qry2EvalSortKey.FieldByName('EVALSORTKEY').AsInteger;
                   FieldByName('IEEVALQTEXT').AsString:=Qry2EvalResult.FieldByName('IEEVALQTEXT').AsString;
                   FieldByName('TTLX').AsInteger:=Qry2EvalResult.FieldByName('TTLX').AsInteger;
                   FieldByName('TTLY').AsInteger:=Qry2EvalResult.FieldByName('TTLY').AsInteger;
                   FieldByName('TTLZ').AsFloat:=Qry2EvalResult.FieldByName('TTLZ').AsFloat;
                   Post;
              end;
              Next;
            end;
               btnIERPrint.Enabled:=True;            
          end else
          begin
               btnIERPrint.Enabled:=False;  
          end;

       end;

       Mem2EvalResultSorted.Open;
       Mem2EvalResultSorted.SortOn('SORTKEY',[]);
       dbgridInsEvalResult.Refresh;
     end;
end;

procedure TfrmMainWindow.btnIERPrintClick(Sender: TObject);
var
AFrmReports:TfrmReports;
repPDF,repPDF2:TQRPDFDocumentFilter;
LDoc: TgtPDFDocument;
NewFilename2,NewFilename3:string;
  pagescount,spage:Integer;
  strSQLPrint:string;
begin

    if dbgridInsEvalResult.RowCount=0 then
     begin
       Application.MessageBox('No Results to print.', 'No Evaluation', MB_ICONEXCLAMATION);
       cboInstructor.DroppedDown;
       cboInstructor.SetFocus;
       Exit;
     end;

     AFrmReports:= TfrmReports.Create(nil);
     AFrmReports.ADOConnection1:=ADOConnection2;
     AFrmReports.Mem2IERSource.EmptyTable;
     if not Mem2EvalResultSorted.IsEmpty then
     begin
       Mem2EvalResultSorted.First;
       while not Mem2EvalResultSorted.Eof do begin
         with AFrmReports.Mem2IERSource do
         begin
              Open;
              Append;
              FieldByName('SORTKEY').AsInteger:=Mem2EvalResultSorted.FieldByName('SORTKEY').AsInteger;
              FieldByName('IEEVALQTEXT').AsString:=Mem2EvalResultSorted.FieldByName('IEEVALQTEXT').AsString;
              FieldByName('TTLX').AsInteger:=Mem2EvalResultSorted.FieldByName('TTLX').AsInteger;
              FieldByName('TTLY').AsInteger:=Mem2EvalResultSorted.FieldByName('TTLY').AsInteger;
              FieldByName('TTLZ').AsFloat:=Mem2EvalResultSorted.FieldByName('TTLZ').AsFloat;
              Post;
         end;
         Mem2EvalResultSorted.Next;
       end;
     end;

     if cbEvalResultDR.Checked then
         AFrmReports.QRLTitleDate.Caption:=formatdatetime('yyyy-mm-dd',dtEvalResultFrom.datetime) + ' - ' + formatdatetime('yyyy-mm-dd',dtEvalResultto.datetime)
     else
         AFrmReports.QRLTitleDate.Caption:=' All ';

    strSQLPrint:='SELECT IEPOSCOMMENT,count(IEPOSCOMMENT) as FREQ1' +
               ' FROM IE' +
               ' WHERE len(IEPOSCOMMENT) >0 and IEINAME=''' + trim(cboInstructor.Text) + '''';
    if cbEvalResultDR.Checked then
       strSQLPrint:= strSQLPrint +' AND IEDOE between ''' + formatdatetime('yyyy-mm-dd',dtEvalResultFrom.datetime) + ' 00:00'' and ''' + formatdatetime('yyyy-mm-dd',dtEvalResultto.datetime) + ' 23:59''';


    with adqTemp do begin
      Close;
      Connection:=ADOConnection2;
      CommandTimeout := 6000; //sarma on jan.23.2013
      SQL.Text := strSQLPrint + ' group by IEPOSCOMMENT';
      Open;
      if not IsEmpty then
      begin
        AFrmReports.QRMEMOPosCom.Lines.Clear;
        First;
        while not Eof do begin
          AFrmReports.QRMEMOPosCom.Lines.Add(trim(FieldByName('IEPOSCOMMENT').AsString) + ' (FREQUENCY(' + trim(FieldByName('FREQ1').AsString)+ ')');
          Next;
        end;
      end;
    end;

    strSQLPrint:='SELECT IENEGCOMMENT,count(IENEGCOMMENT) as FREQ1' +
               ' FROM IE' +
               ' WHERE len(IENEGCOMMENT) >0 and IEINAME=''' + trim(cboInstructor.Text) + '''';
    if cbEvalResultDR.Checked then
       strSQLPrint:= strSQLPrint +' AND IEDOE between ''' + formatdatetime('yyyy-mm-dd',dtEvalResultFrom.datetime) + ' 00:00'' and ''' + formatdatetime('yyyy-mm-dd',dtEvalResultto.datetime) + ' 23:59''';


    with adqTemp do begin
      Close;
      Connection:=ADOConnection2;
      CommandTimeout := 6000; //sarma on jan.23.2013
      SQL.Text := strSQLPrint + ' group by IENEGCOMMENT';
      Open;
      if not IsEmpty then
      begin
        AFrmReports.QRMEMONegCom.Lines.Clear;
        First;
        while not Eof do begin
          AFrmReports.QRMEMONegCom.Lines.Add(trim(FieldByName('IENEGCOMMENT').AsString) + ' (FREQUENCY(' + trim(FieldByName('FREQ1').AsString)+ ')');
          Next;
        end;
      end;
    end;


     AFrmReports.QRLTitleInsName.Caption:=trim(cboInstructor.Text);
    iSubDirectory:=ExtractFilePath(Application.ExeName) + 'Reports';
    FileFind(iSubDirectory,'*','pdf'); // delete existing pdf in the folder.
    NewFilename := '';
    if not DirectoryExists(iSubDirectory) then MkDir(iSubDirectory);
    NewFilename:=iSubDirectory+'\'+CreateClassID+'.pdf';
    repPDF := TQRPDFDocumentFilter.Create(NewFilename);
    AFrmReports.QuickRep1.ExportToFilter(repPDF);
    NewFilename2:=iSubDirectory+'\'+CreateClassID+'.pdf';
    repPDF2 := TQRPDFDocumentFilter.Create(NewFilename2);
    AFrmReports.QuickRep2.ExportToFilter(repPDF2);

     LDoc := TgtPDFDocument.Create(nil);
     if gtPDFDocument1.IsLoaded then
       gtPDFDocument1.reset;

     gtPDFDocument1.LoadFromFile(NewFilename);
     spage:= gtPDFDocument1.PageCount;
     LDoc.LoadFromFile(NewFilename2);

     for pagescount:= 1 to LDoc.PageCount do
     begin
      gtPDFDocument1.InsertPagesFrom(LDoc,IntToStr(pagescount),spage);
      spage:=spage + 1;
     end;

    gtPDFDocument1.SaveToFile(NewFilename,naEnable);
    LDoc.Free;
    ShellExecute(Handle, 'OPEN', PChar(NewFilename), nil, nil, SW_SHOW);
    AFrmReports.Free;

end;

procedure TfrmMainWindow.listCompanyClick(Sender: TObject);
begin
     RegEntryPage.ActivePageIndex:=3;
     QryCompany.Locate('SHIPPINGNAME',trim(listCompany.SelectedItem),[]);
     dbgridCompany.SetFocus;
     //FilterQryBillingReviewee;
end;

procedure TfrmMainWindow.listEndorserClick(Sender: TObject);
begin
     RegEntryPage.ActivePageIndex:=4;
     QryEndorser.Locate('ENDORSERFULL',trim(listEndorser.SelectedItem),[]);
     dbgridEndorser.SetFocus;

end;

procedure TfrmMainWindow.RzBitBtn11Click(Sender: TObject);
begin
     frmPOManagement.ShowModal;
end;

procedure TfrmMainWindow.RzBitBtn12Click(Sender: TObject);
var
   AFrmTemp : TfrmItemRequest;
begin
  AFrmTemp:= TfrmItemRequest.Create(nil);
  AFrmTemp.ADOConnection1:=ADOConnection1;
  AFrmTemp.Caption := 'Item Requisition Module';
//  AFrmTemp.MainPageEmpEval.HideAllTabs;
  AFrmTemp.ShowModal;
  FreeAndNil(AFrmTemp);;
end;

procedure TfrmMainWindow.RzBitBtn15Click(Sender: TObject);
var
   AFrmTemp : TfrmRequestEntry;
begin
  AFrmTemp:= TfrmRequestEntry.Create(nil);
  AFrmTemp.ADOConnection1:=ADOConnection1;
  AFrmTemp.Caption := 'Request Item';
//  AFrmTemp.MainPageEmpEval.HideAllTabs;
  AFrmTemp.ShowModal;
  FreeAndNil(AFrmTemp);
end;
end.



